package com.ruoyi.project.system.user.controller;

import cn.hutool.core.util.ObjectUtil;
import com.ruoyi.common.constant.SystemContstant;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.utils.security.ShiroUtils;
import com.ruoyi.framework.aop.NoRepeatSubmit;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.project.content.PropertyTypeEnum;
import com.ruoyi.project.content.UserTypeEnum;
import com.ruoyi.project.system.post.service.IPostService;
import com.ruoyi.project.system.role.service.IRoleService;
import com.ruoyi.project.system.user.domain.User;
import com.ruoyi.project.system.user.service.IAdminService;
import com.ruoyi.project.system.user.service.IUserService;
import com.ruoyi.project.utils.RedisUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;

/**
 * 用户信息
 *
 * @author ruoyi
 */
@Controller
@RequestMapping ("/system/user")
public class UserController extends BaseController {

    private String prefix = "system/user";

    @Autowired
    private IUserService userService;


    @Autowired
    private IRoleService roleService;

    @Autowired
    private IPostService postService;

    @Autowired
    private RedisUtils redisUtils;


    @Resource (name = "adminServiceImpl")
    private IAdminService adminService;

    @RequiresPermissions ("system:user:view")
    @GetMapping ()
    public String user () {

        return this.prefix + "/user";
    }

    @GetMapping ("/sub_user/{userId}")
    public String subUser (@PathVariable ("userId") Long userId, ModelMap mmap) {
        mmap.put("userId", userId);
        return this.prefix + "/sub_user";
    }

    @GetMapping ("/taskCateUser/{userId}")
    public String taskCateUser (@PathVariable ("userId") Long userId, ModelMap mmap) {
        mmap.put("userId", userId);
        return this.prefix + "/taskCateUser";
    }

    @PostMapping ("/my_cate")
    @ResponseBody
    public TableDataInfo myCate (User user) {
        this.startPage();
        return this.getDataTable(null);
    }



    @RequiresPermissions ("system:common_user:view")
    @GetMapping ("/common")
    public String commonUser (ModelMap mmap) {
        mmap.put("upUrl", this.redisUtils.hget(PropertyTypeEnum.SYS.getText(), SystemContstant.PICURL));
        return this.prefix + "/common_user";
    }


    @RequiresPermissions ("system:user:list")
    @PostMapping ("/list")
    @ResponseBody
    public TableDataInfo list (User user) {
        this.startPage();
        Short userType = user.getUserType();
        if (userType != null && userType == 0) {
            List <User> adminList = this.adminService.findList(user);
            return this.getDataTable(adminList);
        }
        List <User> listty = new ArrayList <User>();
        if (user.getEmail() != null && !user.getEmail().equals("")) {
            if ("3".equals(user.getEmail())) {
                Set <String> listt = this.redisUtils.getByVagueKey(SystemContstant.NO_ORDER_USER + "*");
                for (String key : listt) {
                    String userids = key.substring(18, key.length());
                    User userss = new User();
                    userss.setUserId(Long.valueOf(userids));
                    List <User> users = this.userService.selectUserList(userss);
                    long d = Long.valueOf(this.redisUtils.get(SystemContstant.NO_ORDER_USER + userids));
                    long sd = d - new Date().getTime();
                    users.get(0).setEmail(formatDuring(sd));
                    listty.add(users.get(0));
                }
                return this.getDataTable(listty);

            } else {
                user.setBanStatus(Integer.valueOf(user.getEmail()));
                user.setEmail(null);
            }
        }
        List <User> list = this.userService.findList(user);
        for (int i = 0; i < list.size(); i++) {
            if (this.redisUtils.hasKey(SystemContstant.NO_ORDER_USER + list.get(i).getUserId())) {
                long d = Long.valueOf(this.redisUtils.get(SystemContstant.NO_ORDER_USER + list.get(i).getUserId()));
                long sd = d - new Date().getTime();
                list.get(i).setEmail(formatDuring(sd));
            }
        }
        return this.getDataTable(list);
    }

    /**
     * @param 要转换的毫秒数
     *
     * @return 该毫秒数转换为 * days * hours * minutes * seconds 后的格式
     */
    public static String formatDuring (long mss) {
        long days = mss / (1000 * 60 * 60 * 24);
        long hours = (mss % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60);
        long minutes = (mss % (1000 * 60 * 60)) / (1000 * 60);
        long seconds = (mss % (1000 * 60)) / 1000;
        return days + "天" + hours + "小时" + minutes + "分钟" + seconds + "秒";
    }

    @Log (title = "用户管理", businessType = BusinessType.EXPORT)
    @RequiresPermissions ("system:user:export")
    @PostMapping ("/export")
    @ResponseBody
    public AjaxResult export (User user) {
        List <User> list = this.userService.selectUserList(user);
        ExcelUtil <User> util = new ExcelUtil <User>(User.class);
        return util.exportExcel(list, "用户数据",null);
    }

    @Log (title = "用户管理", businessType = BusinessType.IMPORT)
    @RequiresPermissions ("system:user:import")
    @PostMapping ("/importData")
    @ResponseBody
    public AjaxResult importData (MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil <User> util = new ExcelUtil <User>(User.class);
        List <User> userList = util.importExcel(file.getInputStream());
        String message = this.userService.importUser(userList, updateSupport);
        return AjaxResult.success(message);
    }

    @RequiresPermissions ("system:user:view")
    @GetMapping ("/importTemplate")
    @ResponseBody
    public AjaxResult importTemplate () {
        ExcelUtil <User> util = new ExcelUtil <User>(User.class);
        return util.importTemplateExcel("用户数据",null);
    }

    /**
     * 新增用户
     */
    @GetMapping ("/add")
    public String add (ModelMap mmap) {
        mmap.put("roles", this.roleService.selectRoleAll());
        mmap.put("posts", this.postService.selectPostAll());
        return this.prefix + "/add";
    }

    /**
     * 新增保存用户
     */
    @RequiresPermissions ("system:user:add")
    @Log (title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping ("/add")
    @ResponseBody
    public AjaxResult addSave (@Validated User user) {
        if (UserConstants.USER_NAME_NOT_UNIQUE.equals(this.userService.checkLoginNameUnique(user.getLoginName()))) {
            return this.error("新增用户'" + user.getLoginName() + "'失败，登录账号已存在");
        } else if (UserConstants.USER_PHONE_NOT_UNIQUE.equals(this.userService.checkPhoneUnique(user))) {
            return this.error("新增用户'" + user.getLoginName() + "'失败，手机号码已存在");
        }
        user.setUserType(UserTypeEnum.SYS_USER.getValue().shortValue());
        return this.toAjax(this.userService.insertUser(user));
    }

    /**
     * 修改用户
     */
    @GetMapping ("/edit/{userId}")
    public String edit (@PathVariable ("userId") Long userId, ModelMap mmap) {
        mmap.put("user", this.userService.selectUserById(userId));
        mmap.put("roles", this.roleService.selectRolesByUserId(userId));
        mmap.put("posts", this.postService.selectPostsByUserId(userId));
        return this.prefix + "/edit";
    }

    @GetMapping ("/common_edit/{userId}")
    public String commonEdit (@PathVariable ("userId") Long userId, ModelMap mmap) {
        mmap.put("userId", userId);
        mmap.put("user", this.userService.selectUserById(userId));
        return this.prefix + "/common_edit";
    }


    @GetMapping ("/add_coupon/{userId}")
    public String addCoupon (@PathVariable ("userId") Long userId, ModelMap mmap) {
        mmap.put("user", this.userService.selectUserById(userId));
        return "bajiaostar/coupon/add";
    }

    @GetMapping ("/add_coupons")
    public String addCoupons () {
        return "bajiaostar/coupon/batch_add";
    }

    /**
     * 卡片跳转
     *
     * @param userId
     *
     * @return
     */
    @GetMapping ("/updosage/{userId}")
    public String updosage (@PathVariable ("userId") Long userId, ModelMap mmap) {
        System.out.print("user+++++++++++++++++" + userId);
        mmap.put("user", this.userService.selectUserById(userId));
        return this.prefix + "/adddosage";
    }


    /**
     * 修改保存用户
     */
    @RequiresPermissions ("system:user:edit")
    @Log (title = "用户管理", businessType = BusinessType.UPDATE)
    @PostMapping ("/edit")
    @ResponseBody
    public AjaxResult editSave (@Validated User user) {
        if (StringUtils.isNotNull(user.getUserId()) && User.isAdmin(user.getUserId())) {
            return this.error("不允许修改超级管理员用户");
        } else if (UserConstants.USER_PHONE_NOT_UNIQUE.equals(this.userService.checkPhoneUnique(user))) {
            return this.error("修改用户'" + user.getLoginName() + "'失败，手机号码已存在");
        } else if (UserConstants.USER_EMAIL_NOT_UNIQUE.equals(this.userService.checkEmailUnique(user))) {
            return this.error("修改用户'" + user.getLoginName() + "'失败，邮箱账号已存在");
        }
        user.setUpdateBy(ShiroUtils.getLoginName());
        return this.toAjax(this.userService.updateUser(user));
    }

    @RequiresPermissions ("system:user:resetPwd")
    @Log (title = "重置密码", businessType = BusinessType.UPDATE)
    @GetMapping ("/resetPwd/{userId}")
    public String resetPwd (@PathVariable ("userId") Long userId, ModelMap mmap) {
        mmap.put("user", this.userService.selectUserById(userId));
        return this.prefix + "/resetPwd";
    }

    @RequiresPermissions ("system:user:resetPwd")
    @Log (title = "重置密码", businessType = BusinessType.UPDATE)
    @PostMapping ("/resetPwd")
    @ResponseBody
    public AjaxResult resetPwdSave (User user) {
        if (this.userService.resetUserPwd(user) > 0) {
            if (ShiroUtils.getUserId().equals(user.getUserId())) {
                this.setSysUser(this.userService.selectUserById(user.getUserId()));
            }
            return this.success();
        }
        return this.error();
    }



    @RequiresPermissions ("system:user:remove")
    @Log (title = "用户管理", businessType = BusinessType.DELETE)
    @PostMapping ("/remove")
    @ResponseBody
    public AjaxResult remove (String ids) {
        try {
            return this.toAjax(this.userService.deleteUserByIds(ids));
        } catch (Exception e) {
            return this.error(e.getMessage());
        }
    }

    /**
     * 校验用户名
     */
    @PostMapping ("/checkLoginNameUnique")
    @ResponseBody
    public String checkLoginNameUnique (User user) {
        return this.userService.checkLoginNameUnique(user.getLoginName());
    }

    /**
     * 校验手机号码
     */
    @PostMapping ("/checkPhoneUnique")
    @ResponseBody
    public String checkPhoneUnique (User user) {
        return this.userService.checkPhoneUnique(user);
    }

    /**
     * 校验email邮箱
     */
    @PostMapping ("/checkEmailUnique")
    @ResponseBody
    public String checkEmailUnique (User user) {
        return this.userService.checkEmailUnique(user);
    }

    /**
     * 用户状态修改
     */
    @Log (title = "用户管理", businessType = BusinessType.UPDATE)
    @RequiresPermissions ("system:user:edit")
    @PostMapping ("/changeStatus")
    @ResponseBody
    public AjaxResult changeStatus (User user) {
        return this.toAjax(this.userService.changeStatus(user));
    }


    @Log (title = "用户管理", businessType = BusinessType.UPDATE)
    @RequiresPermissions ("system:user:edit")
    @PostMapping ("/updFlags")
    @ResponseBody
    public AjaxResult updFlags (Long userId, Integer flag, Integer type) {

        //User user = userService.selectUserById(userId);
       /* if (user==null){
            return error("当前用户信息错误");
        }*/
        int i = 0;
        if (type == 0) {
            i = this.userService.updateVipBygoldmedallevelone(userId);
        } else if (type == 1) {
            i = this.userService.updateVipBygoldmedallevelone(userId);
        } else if (type == 2) {
            i = this.userService.updateVipBygoldmedalleveltwe(userId);
        } else {
            return this.error("类型不存在");
        }
        return this.toAjax(i);
    }



}